<script setup lang="ts">
    import { ref, onMounted } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    import { showConfirmDialog, showToast } from 'vant'
    import { orderDetailAPIRes, orderCanceAPIRes, orderDelAPIRes, orderFinishAPIRes } from '@/api'
    import { useOrder } from '@/store/order'

    const { query } = useRoute()
    const useorder = useOrder()
    const router = useRouter()
    const canceShow = ref(false)
    const refundDesc = ref('')
    const detail = ref<any>({})
    const addClockShow = ref(false)
    const addClockActions = ref([
        {
            name: '加时长',
            callback: () => {
                router.push({
                    path: '/product/add',
                    query: { tid: detail.value.tid, pid: detail.value.pid, aid: detail.value.aid, orderNo: detail.value.orderNo, name: detail.value.name, type: 1 }
                })
            }
        }, {
            name: '加项目',
            callback: async () => {
                router.push({
                    path: '/product/add',
                    query: { tid: detail.value.tid, pid: detail.value.pid, aid: detail.value.aid, orderNo: detail.value.orderNo, type: 2 }
                })
            }
        }
    ])

    const getDetail = async () => {
        const { data } = await orderDetailAPIRes({ orderNo: query.orderNo })
        detail.value = data
    }
    // 删除订单
    const onDel = async () => {
        showConfirmDialog({
            message: '是否确定删除此订单？',
            confirmButtonText: '是',
            cancelButtonText: '否'
        }).then(async () => {
            await orderDelAPIRes(detail.value.orderNo)
            router.replace({ path: '/' })
        })
    }
    // 取消订单
    const onCanceShow = () => {
        refundDesc.value = ''
        canceShow.value = true
    }
    const onCance = () => {
        let msg = '是否确认取消此订单？'
        let refundAmount = detail.value.totalAmount
        if (!detail.value.associationOrderNo && detail.value.orderType < 3 && (detail.value.status == 3 && detail.value.sallyPhoto || detail.value.status == 4)) {
            msg = `技师已经${detail.value.status == 4 ? '到达' : '出发'}，取消订单将扣取车费，是否确认取消此订单？`
            refundAmount = detail.value.totalAmount - detail.value.fareAmount
        }
        canceShow.value = false
        showConfirmDialog({
            message: msg,
            confirmButtonText: '是',
            cancelButtonText: '否'
        }).then(async () => {
            const obj = {
                orderNo: detail.value.orderNo,
                associationOrderNo: detail.value.associationOrderNo,
                refundDesc: refundDesc.value,
                refundAmount,
                totalAmount: detail.value.totalAmount,
                fareAmount: detail.value.fareAmount,
                status: detail.value.status,
                tid: detail.value.tid,
                productName: detail.value.name,
                cid: detail.value.cid
            }
            await orderCanceAPIRes(obj)
            getDetail()
        })
    }
    // 修改项目
    const onUpdate = () => {
        router.push({
            path: '/product/edit',
            query: { tid: detail.value.tid, pid: detail.value.pid, aid: detail.value.aid, orderNo: detail.value.orderNo }
        })
    }
    // 完成订单
    const onFinish = async () => {
        showConfirmDialog({
            message: '是否确定结束此订单服务？',
            confirmButtonText: '是',
            cancelButtonText: '否'
        }).then(async () => {
            await orderFinishAPIRes({ orderNo: detail.value.orderNo })
            getDetail()
        })
    }
    // 点击复制订单号
    const copyToClipboard = () => {
        navigator.clipboard.writeText(detail.value.orderNo).then(() => {
            showToast('复制成功')
        }).catch(err => {
            showToast('复制失败')
            console.log('复制失败', err)
        })
    }

    onMounted(async() => {
        getDetail()
    })
</script>

<template>
    <van-nav-bar fixed placeholder left-arrow @click-left="router.back()">
        <template #title>
            <template v-if="detail.status == 1">待接单</template>
            <template v-if="detail.status == 2">已接单</template>
            <template v-if="detail.status == 3">已出发</template>
            <template v-if="detail.status == 4">已到达</template>
            <template v-if="detail.status == 5">服务中</template>
            <template v-if="detail.status > 5 && detail.status < 30">服务完成</template>
            <template v-if="detail.status == 30">已取消</template>
        </template>
    </van-nav-bar>
    <van-cell-group inset class="p-2.5 my-2.5">
        <div class="flex items-center">
            <van-image
                radius="8"
                width="4rem"
                height="4rem"
                fit="cover"
                :src="detail.productImg"
            />
            <div class="flex-1 flex flex-col justify-between ml-2.5">
                <div class="flex items-center text-base font-bold text-[#333]">
                    <spna>{{ detail.name }}</spna>
                    <spna v-if="detail.orderType == 2">（改项目）</spna>
                    <spna v-if="detail.orderType == 3">（时长加钟）</spna>
                    <spna v-if="detail.orderType == 4">（项目加钟）</spna>
                </div>
                <div class="text-sm text-[#666]">服务技师：{{ detail.nickname }}</div>
                <div class="text-sm text-[#666]">服务时长：
                    <span v-if="detail.addTimeType == 1">20分钟</span>
                    <span v-else-if="detail.addTimeType == 2">30分钟</span>
                    <span v-else-if="detail.addTimeType == 3">40分钟</span>
                    <span v-else>{{ detail.duration }}分钟</span>
                </div>
            </div>
        </div>
        <van-cell title="项目费用" :border="false" class="p-0 py-1">
            <span class="text-[#333]">
                <span>￥</span>
                <span v-if="detail.addTimeType == 1">80.00</span>
                <span v-else-if="detail.addTimeType == 2">100.00</span>
                <span v-else-if="detail.addTimeType == 3">120.00</span>
                <span v-else>{{ (detail.price || 0).toFixed(2) }}</span>
            </span>
        </van-cell>
        <van-cell title="车费" :border="false" class="p-0 py-1">
            <span class="text-[#333]">¥{{ (detail.fareAmount || 0).toFixed(2) }}</span>
        </van-cell>
        <van-cell title="优惠劵" :border="false" class="p-0 py-1">
            <span class="text-[#333]">-¥{{ (detail.discountAmount || 0).toFixed(2) }}</span>
        </van-cell>
        <van-cell title="实付款" :border="false" class="p-0 py-1">
            <span class="text-[#333]">¥{{ (detail.totalAmount || 0).toFixed(2) }}</span>
        </van-cell>
    </van-cell-group>
    <van-cell-group inset class="p-2.5 mb-2.5">
        <van-cell title="下单人" center :border="false" class="p-0 py-1">
            <span class="text-[#333]">{{ detail.userName }}</span>
        </van-cell>
        <van-cell title="联系方式" center :border="false" class="p-0 py-1">
            <span class="text-[#333]">{{ detail.phone }}</span>
        </van-cell>
        <van-cell title="服务地址" :border="false" class="p-0 py-1" title-class="flex-none mr-4">
            <span class="text-[#333]">{{ detail.province + detail.address }}</span>
        </van-cell>
    </van-cell-group>
    <van-cell-group inset class="p-2.5 mb-2.5">
        <van-cell title="订单号" center :border="false" title-class="flex-none" class="p-0 py-1">
            <span class="text-[#333] mr-1" @click="copyToClipboard">{{ detail.orderNo }}</span>
            <template #right-icon>
                <van-button size="mini" @click.stop="copyToClipboard">复制</van-button>
            </template>
        </van-cell>
        <van-cell title="下单时间" center :border="false" class="p-0 py-1">
            <span class="text-[#333]">{{ detail.createTime }}</span>
        </van-cell>
        <van-cell v-if="detail.status == 30" title="取消时间" center :border="false" class="p-0 py-1">
            <span class="text-[#333]">{{ detail.cancelTime }}</span>
        </van-cell>
        <van-cell v-if="detail.status == 30" title="取消原因" center :border="false" class="p-0 py-1">
            <span class="text-[#333]">{{ detail.refundDesc }}</span>
        </van-cell>
        <van-cell title="出行方式" center :border="false" class="p-0 py-1">
            <span class="text-[#333]">打车(单程{{ (detail.distance / 2 / 500).toFixed(2) }}公里)</span>
        </van-cell>
        <van-cell title="支付方式" center :border="false" class="p-0 py-1">
            <span class="text-[#333]">{{ detail.payType == 1 ? '微信支付' : '余额支付' }}</span>
        </van-cell>
    </van-cell-group>
    <van-cell-group v-if="detail.speed && detail.speed.length > 0" inset class="p-2.5 mb-2.5">
        <van-steps :active="detail.speed.length - 1" direction="vertical" active-color="#7C6186">
            <van-step v-for="(item, index) in detail.speed" ::key="index">
                <h3>{{ item.statusDesc }}</h3>
                <p>{{ item.updatedAt }}</p>
            </van-step>
        </van-steps>
    </van-cell-group>
    <div class="h-14 p-2.5 van-safe-area-bottom box-content"></div>
    <div class="fixed bottom-0 left-0 right-0 p-2.5 text-right z-10 bg-white van-safe-area-bottom ">
        <van-space class="pb-2.5">
            <van-button v-if="detail.status < 5" @click="onCanceShow">取消订单</van-button>
            <van-button v-if="detail.status > 5" @click="onDel">删除订单</van-button>
            <van-button v-if="detail.status < 5 && detail.orderType == 1" color="#7C6186" @click="onUpdate">改项目</van-button>
            <van-button v-if="detail.status == 5" color="#7C6186" @click="addClockShow = true">加钟</van-button>
            <van-button v-if="detail.status == 5" color="#7C6186" @click="onFinish">服务完成</van-button>
        </van-space>
    </div>
    <!-- 取消弹窗 -->
    <van-popup v-model:show="canceShow" safe-area-inset-bottom round position="bottom" class="h-auto">
        <van-nav-bar title="取消订单" />
        <van-radio-group v-model="refundDesc">
            <van-cell-group inset :border="false">
                <van-cell v-for="(item, index) in useorder.refundDesc" ::key="index" :title="item" clickable :border="false" @click="refundDesc = item">
                    <template #right-icon>
                        <van-radio :name="item" checked-color="#7C6186" />
                    </template>
                </van-cell>
            </van-cell-group>
        </van-radio-group>
        <div class="flex items-center justify-between p-4">
            <van-button block round class="mr-2" @click="canceShow = false">暂不取消</van-button>
            <van-button block round class="ml-2" color="#7C6186" @click="onCance">确定取消</van-button>
        </div>
    </van-popup>
     <!-- 加钟选项 -->
     <van-action-sheet
        v-model:show="addClockShow"
        :actions="addClockActions"
        cancel-text="取消"
        close-on-click-action
        @cancel="addClockShow = false"
    />
</template>